package zfbh5

import (
	"github.com/gin-gonic/gin"
	"time"
	"yundian/internel/pkg/dingo/global"

	"yundian/internel/app/dao"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/devices"
	"yundian/internel/app/models/smscode"
	"yundian/internel/pkg/dingo"
	. "yundian/internel/pkg/dingo/result"
	"yundian/internel/pkg/utils"
	"yundian/internel/pkg/utils/sms"
)

// HandleSetPlaceDeviceUnbind 门店设备解绑
func HandleSetPlaceDeviceUnbind(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.AppSetPlaceDeviceBindingReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.LoginUserId = userId

	placeData := dao.NewUsersStaffDao().GetStaffUserPlacesListById(param.LoginUserId)
	placeList := placeData.Unwrap().([]*request.StewardAppGetPlacesRes)
	if len(placeList) <= 0 {
		Response(ctx)("", CodeInvalidParam, nil)(OK)
		return
	}

	deviceInfo := dao.NewDeviceDao().GetDeviceByDeviceSn(param.DeviceSn).Unwrap().(*devices.DeviceModel)
	for index, item := range placeList {
		if deviceInfo.PlaceId == item.PlaceId {
			continue
		}
		if index == len(placeList)-1 {
			return
		}
	}
	if dao.NewDeviceDao().SetDeviceUnbind(deviceInfo).Err != nil {
		Response(ctx)("", CodeInternalServerError, nil)(OK)
		return
	}

	Response(ctx)("", CodeSuccess, true)(OK)
}

// HandleSetPlaceDeviceBinding 门店设备绑定
func HandleSetPlaceDeviceBinding(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.AppSetPlaceDeviceBindingReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.LoginUserId = userId

	placeData := dao.NewUsersStaffDao().GetStaffUserPlacesInfoById(param.LoginUserId, param.PlaceId)
	placeInfo := placeData.Unwrap().(*request.StewardAppGetPlacesRes)
	if placeInfo.PlaceId <= 0 {
		Response(ctx)("", CodeInvalidParam, nil)(OK)
		return
	}

	deviceInfo := dao.NewDeviceDao().GetDeviceByDeviceSn(param.DeviceSn).Unwrap().(*devices.DeviceModel)
	if deviceInfo.PlaceId == 0 && deviceInfo.ID > 0 {
		deviceInfo.PlaceName = placeInfo.PlaceName
		deviceInfo.PlaceId = placeInfo.PlaceId
		if dao.NewDeviceDao().SetDeviceBinding(deviceInfo).Err != nil {
			Response(ctx)("", CodeInternalServerError, nil)(OK)
			return
		}
	} else if deviceInfo.PlaceId != param.PlaceId && deviceInfo.PlaceId != 0 {
		Response(ctx)("", CodeInvalidParam, nil)(OK)
		return
	}

	if roomData := dao.NewDeviceDao().SetStewardDevice(&request.SetStewardDeviceReq{
		PlaceId:  param.PlaceId,
		DeviceSn: param.DeviceSn,
		Room:     param.Room,
		Status:   helper.TypeNumRoomStatusLeisure,
	}); roomData.Err != nil {
		Response(ctx)("", CodeInternalServerError, nil)(OK)
		return
	}

	Response(ctx)("", CodeSuccess, true)(OK)
}

// HandleSetAppStaffInformMessageStatus 消息已读
func HandleSetAppStaffInformMessageStatus(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.AppGetStaffInformMessageListReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.LoginUserId = userId

	if dao.NewBulletinDao().SetAppStaffInformMessageStatus(param).Err != nil {
		Response(ctx)("", CodeInternalServerError, nil)(OK)
		return
	}
	Response(ctx)("", CodeSuccess, true)(OK)
}

// HandleGetAppStaffInformMessageList 查询消息列表
func HandleGetAppStaffInformMessageList(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.AppGetStaffInformMessageListReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.LoginUserId = userId

	data := dao.NewBulletinDao().GetAppStaffInformMessageList(param)
	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       data.Unwrap(),
	})(OK)
}

// HandleAppSetAccountPhone 绑定帐号手机号
func HandleAppSetAccountPhone(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.AppSmsCodeReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.LoginUserId = userId

	if checkInt := dao.NewUserDao().GetSmsCodeInfo(param.Phone, param.Code).Unwrap().(int64); checkInt <= 0 {
		Response(ctx)("验证码错误", CodeInvalidParam, false)(OK)
		return
	}

	if dao.NewUsersStaffDao().SetStaffUserPhone(param).Err != nil {
		Response(ctx)("更新失败，请联系管理员", CodeInternalServerError, true)(OK)
		return
	}

	Response(ctx)("", CodeSuccess, true)(OK)
}

// HandleAppSendSmsCode 发送验证码
func HandleAppSendSmsCode(ctx *gin.Context) {
	//userId, err := helper.GetUserIdFromCtx(ctx)
	//dingo.ErrorIf(err).Unwrap()

	param := &request.AppSmsCodeReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	//param.LoginUserId = userId

	reqCount := dao.NewUserDao().GetUserSmsCodeCount(param.Phone, int(time.Now().Unix())).Unwrap().(int64)
	if reqCount > 10 {
		Response(ctx)("今天请求次数上限", CodeInvalidParam, false)(OK)
		return
	}

	response, code, err := sms.SmsAliParams(param.Phone)
	if err != nil || response.Code != "OK" || response.Message != "OK" {
		Response(ctx)("短信发送失败", CodeInvalidParam, err)(OK)
		return
	}
	smsCodeModel := &smscode.SmsCode{}
	smsCodeModel.Code = code
	smsCodeModel.Phone = param.Phone
	smsCodeModel.Status = 2
	smsCodeModel.CreateAt = dingo.Time(time.Now().Unix())
	dao.NewUserDao().InsertSmsCode(smsCodeModel)

	Response(ctx)("", CodeSuccess, true)(OK)
}

// HandleGetPlaceRoomList 查询服务数量(总)
func HandleGetPlaceRoomList(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.AppGetPlaceRoomListReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.LoginUserId = userId

	data := dao.NewRoomDaoDao().GetPlaceRoomList(param)
	Response(ctx)("", CodeSuccess, data.Unwrap())(OK)
}

// HandleSetUserInfo 设置员工信息
func HandleSetUserInfo(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.AppSetUserInfoReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.LoginUserId = userId

	if dao.NewUsersStaffDao().SetUserInfo(param).Err != nil {
		Response(ctx)("", CodeInternalServerError, false)(OK)
		return
	}

	Response(ctx)("", CodeUpdateSuccess, true)(OK)
}

// HandleSetUserOnlineStatus 设置员工在线状态
func HandleSetUserOnlineStatus(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.SetUserOnlineStatusReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.LoginUserId = userId

	if dao.NewUsersStaffDao().SetUserOnlineStatus(param).Err != nil {
		Response(ctx)("", CodeInternalServerError, false)(OK)
		return
	}

	Response(ctx)("", CodeUpdateSuccess, true)(OK)
}

// HandleSetLoginUserPassword 修改登录用户密码
func HandleSetLoginUserPassword(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.SetLoginUserPasswordReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	if param.Password == "" {
		Response(ctx)("", CodeInvalidParam, nil)(OK)
		return
	}

	password := utils.EncryptPassword(param.Password)
	oldPassword := utils.EncryptPassword(param.OldPassword)
	userInfoData := dao.NewUsersStaffDao().GetStaffUserInfoAllById(userId)
	if oldPassword != userInfoData.Password {
		Response(ctx)("旧密码错误", CodeInvalidParam, nil)(OK)
		return
	}

	Response(ctx)("", CodeUpdateSuccess, dao.NewUsersStaffDao().UpdateUserPassword(userId, password).Unwrap())(OK)
}

// HandleGetStaffUserOpenid 查询员工openid信息
func HandleGetStaffUserOpenid(ctx *gin.Context) {
	loginUserId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	data := dao.NewUsersStaffDao().GetStaffUserOpenidById(loginUserId)
	Response(ctx)("", CodeSuccess, data.Unwrap())(OK)
}

// HandleGetStaffUserInfo 查询员工用户信息
func HandleGetStaffUserInfo(ctx *gin.Context) {
	loginUserId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	data := dao.NewUsersStaffDao().GetStaffUserInfoById(loginUserId)
	placeList := dao.NewUsersStaffDao().GetStaffUserPlacesListById(loginUserId).Unwrap().([]*request.StewardAppGetPlacesRes)

	Response(ctx)("", CodeSuccess, map[string]interface{}{
		"host":      global.Cfg.Ali.AliossPath,
		"userInfo":  data,
		"placeList": placeList,
	})(OK)
}

// HandleGetServiceNum 查询服务数量
func HandleGetServiceNum(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.StewardAppGetServiceNumReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.MessageTypes, _ = helper.GetUserMessageTypesFromCtx(ctx)
	param.LoginUserId = userId

	data := dao.NewNotificationDaoDao().GetAppNotificationServiceInfo(param)
	Response(ctx)("", CodeSuccess, data.Unwrap())(OK)
}

// HandleGetServiceTotal 查询服务数量(总)
func HandleGetServiceTotal(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.StewardAppGetServiceNumReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.MessageTypes, _ = helper.GetUserMessageTypesFromCtx(ctx)
	param.LoginUserId = userId

	r := &request.StewardAppGetServiceTotalRes{}
	param.Status = helper.TypeNumNotificationStatusPending
	r.Pending = dao.NewNotificationDaoDao().GetAppNotificationServiceInfoTotal(param).Unwrap().(*request.StewardAppGetServiceNumRes).Num

	param.Status = helper.TypeNumNotificationStatusProgress
	r.Progress = dao.NewNotificationDaoDao().GetAppNotificationServiceInfoTotal(param).Unwrap().(*request.StewardAppGetServiceNumRes).Num

	param.Status = helper.TypeNumNotificationStatusFinish
	r.Finished = dao.NewNotificationDaoDao().GetAppNotificationServiceInfoTotal(param).Unwrap().(*request.StewardAppGetServiceNumRes).Num
	Response(ctx)("", CodeSuccess, r)(OK)
}
